// 虚拟dom元素的类
class Element {
  constructor(type, props, children) {
    this.type = type
    this.props = props
    this.children = children
  }
}

// 创建并返回虚拟节点
function createElement(type, props, children) {
  return new Element(type, props, children)
}

// 设置属性
function setAttr(node, key, value) {
  switch (key) {
    case 'value':
      if (node.tagName.toUpperCase() === 'INPUT' || node.tagName.toUpperCase() === 'TEXTAREA') {
        node.value = value
      } else {
        node.setAttribute(key, value)
      }
      break;
    case 'style':
      node.style.cssText = value
      break
    default:
      node.setAttribute(key, value)
      break;
  }
}

// render 方法，转化虚拟dom为真实dom
function render(eleObj) {
  let el = document.createElement(eleObj.type)
  for (const key in eleObj.props) {
    // 调用设置属性的方法
    setAttr(el, key, eleObj.props[key])
  }
  eleObj.children.forEach(child => {
    // 判断子元素是否是节点元素 (通过原型判断)
    let childEl = (child instanceof Element) ? render(child) : document.createTextNode(child)
    el.appendChild(childEl)
  })
  return el
}

// 渲染页面 (把真实dom插入到页面)
function renderDom(el, target) {
  target.appendChild(el)
}

export {
  createElement,
  render,
  Element,
  renderDom,
  setAttr
}